package com.hivis.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.hivis.utils.TokenUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

public class LoginInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getServletPath();
        String token = request.getHeader("token");
        // 将请求参数转化为map，以便后续校验签名
        Map<String, String[]> parameterMap = request.getParameterMap();
        Map<String, Object> param = new HashMap<String, Object>();
        buildParamMap(parameterMap, param);

//        String access_token = (String) param.get("access_token");
        Map<String, Object> retMsg = new HashMap<>();
        // 如果tocken验证通过,则放行
//        if (TokenUtil.verify(token)) {
//            return true;
//        } else {
//            retMsg.put("errcode", 40014);
//            retMsg.put("errmsg", "不合法的access_token");
//            sendMessage(response, JSONObject.toJSONString(retMsg));
//
//        }
//        return false;
        return true;
    }

    private void buildParamMap(Map<String, String[]> parameterMap, Map<String, Object> param) {
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            String key = entry.getKey();
            String[] value = entry.getValue();
            if (value != null && value.length > 0) {
                if (!StringUtils.isEmpty(value[0])) {
                    param.put(key, value[0]);
                }
            } else {
                continue;
            }
        }
    }

    private void sendMessage(HttpServletResponse response, String str) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            writer.print(str);
            response.flushBuffer();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            if(writer != null){
                writer.close();
            }
        }

    }
}
